<?php

/**
 * ECSHOP 专题管理
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: topic.php 17217 2011-01-19 06:29:08Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

/* act操作项的初始化 */
if (empty($_REQUEST['act']))
{
    $_REQUEST['act'] = 'list';
}
else
{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}
require_once(ROOT_PATH . 'includes/cls_image.php');
$image = new cls_image($_CFG['bgcolor']);
$exc = new exchange($ecs->table('exam'), $db, 'exam_id','');
$exc2 = new exchange($ecs->table('exam_question'), $db, 'question_id','');
$exc3 = new exchange($ecs->table('exam_result'), $db, 'result_id','');

/* 配置风格颜色选项 */

$allow_suffix = array('gif', 'jpg', 'png', 'jpeg', 'bmp', 'swf');

/*------------------------------------------------------ */
//-- 专题列表页面
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list')
{
    admin_priv('ceping');

    $smarty->assign('ur_here',     $_LANG['18_ceping']);

    $smarty->assign('full_page',   1);
    $list = get_exam_list();

    $smarty->assign('exam_list',   $list['item']);
    $smarty->assign('filter',       $list['filter']);
    $smarty->assign('record_count', $list['record_count']);
    $smarty->assign('page_count',   $list['page_count']);

    $sort_flag  = sort_flag($list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    assign_query_info();
    $smarty->assign('action_link', array('text' => '添加套题', 'href' => 'ceping.php?act=add_exam'));
    $smarty->display('ceping_list.htm');
}
/* 添加,编辑 */
if ($_REQUEST['act'] == 'add_exam' || $_REQUEST['act'] == 'edit_exam')
{
    admin_priv('ceping');

    $isadd     = $_REQUEST['act'] == 'add_exam';
    $smarty->assign('isadd', $isadd);
    $exam_id  = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);


    $smarty->assign('ur_here',     $_LANG['18_ceping']);
    $smarty->assign('action_link', array('href' => 'ceping.php?act=list', 'text' => '套题列表'));
    assign_query_info();
    $smarty->assign('cfg_lang',   $_CFG['lang']);

    if (!$isadd)
    {
        $sql = "SELECT * FROM " . $ecs->table('exam') . " WHERE exam_id = '$exam_id'";
        $exam = $db->getRow($sql);
        


        $smarty->assign('exam', $exam);
        $smarty->assign('act',   "update_exam");
    }
    else
    {
    	$smarty->assign('exam', array('ordering'=>0));
        $smarty->assign('act', "insert_exam");
    }
    $smarty->display('ceping_info.htm');
}
elseif ($_REQUEST['act'] == 'insert_exam' || $_REQUEST['act'] == 'update_exam')
{
    admin_priv('ceping');

    $is_insert = $_REQUEST['act'] == 'insert_exam';
    $exam_id  = empty($_POST['id']) ? 0 : intval($_POST['id']);
   
    if ($_FILES['icon']['size']>0)
    {
    	/* 检查图片：如果有错误，检查尺寸是否超过最大值；否则，检查文件类型 */
    	if (isset($_FILES['icon']['error'])) // php 4.2 版本才支持 error
    	{
    		// 最大上传文件大小
    		$php_maxsize = ini_get('upload_max_filesize');
    		$htm_maxsize = '2M';
    	
    	
    		if ($_FILES['icon']['error'] == 0)
    		{
    			if (!$image->check_img_type($_FILES['icon']['type']))
    			{
    				sys_msg('图片格式不正确！', 1, array(), false);
    			}
    		}
    		elseif ($_FILES['icon']['error'] == 1)
    		{
    			sys_msg('图片文件太大了（最大值：'.$php_maxsize.'），无法上传。', 1, array(), false);
    		}
    		elseif ($_FILES['icon']['error'] == 2)
    		{
    			sys_msg('图片文件太大了（最大值：'.$htm_maxsize.'），无法上传。', 1, array(), false);
    		}
    	
    	
    	}
    	/* 4.1版本 */
    	else
    	{
    		if ($_FILES['icon']['tmp_name'] != 'none')
    		{
    			if (!$image->check_img_type($_FILES['icon']['type']))
    			{
    	
    				sys_msg('图片格式不正确！', 1, array(), false);
    			}
    		}
    	
    	
    	}
    	
    	
    	$icon   = $image->upload_image($_FILES['icon'],'examimg/'.date('Ymd')); // 原始图片
    	 
    	if ($icon === false)
    	{
    		sys_msg($image->error_msg(), 1, array(), false);
    	}
    }
    else $icon = '';
 

    $title = $_POST['title'];
    $content   = addslashes($_POST['content']);
    $ordering= intval($_POST['ordering']);

    if ($is_insert)
    {
    	$created = gmtime();
        $sql = "INSERT INTO " . $ecs->table('exam') . " (title,content,created,ordering,icon) " .
                "VALUES ('$title','$content','$created','$ordering', '$icon')";
        admin_log($title, 'add', 'ceping');
    }
    else
    {
    	if (!empty($icon))
    	{
    		/* 删除原来的图片文件 */
    		$sql = "SELECT icon " .
    				" FROM " . $ecs->table('exam') .
    				" WHERE exam_id = '$exam_id'";
    		$row = $db->getRow($sql);
    		if ($row['icon'] != '' && is_file('../' . $row['icon']))
    		{
    			@unlink('../' . $row['icon']);
    		}
    		
    		$sql = "UPDATE " . $ecs->table('exam') .
                "SET icon='$icon' WHERE exam_id='$exam_id' LIMIT 1";
    		$db->query($sql);
    	}
    	
    	
        $sql = "UPDATE " . $ecs->table('exam') .
                "SET title='$title',content='$content',ordering='$ordering'" .
               " WHERE exam_id='$exam_id' LIMIT 1";
        admin_log($title, 'edit', 'ceping');

    }

    $db->query($sql);
    
    clear_cache_files();

    $links[] = array('href' => 'ceping.php', 'text' =>  '返回套题列表');
    sys_msg('操作成功', 0, $links);
}
elseif ($_REQUEST['act'] == 'question')
{
	admin_priv('ceping');
	$smarty->assign('full_page',   1);
	
	$exam_id = intval($_REQUEST['id']);
	if (!$exam = $db->getRow('SELECT exam_id,title FROM '.$ecs->table('exam').' WHERE exam_id='.$exam_id)){
		sys_msg('套题不存在',1);
	}
	$sql = 'SELECT * FROM '.$ecs->table('exam_question').' WHERE exam_id='.$exam_id;
	$list = $db->getAll($sql);
	$smarty->assign('ur_here',     $exam['title'].'-题目列表');
	$smarty->assign('exam_id',$exam_id);
	$smarty->assign('question_list',   $list);
	assign_query_info();
	$smarty->assign('action_link', array('text' => '添加题目', 'href' => 'ceping.php?act=add_question&exam_id='.$exam_id));
	$smarty->assign('action_link2', array('text' => '套题列表', 'href' => 'ceping.php?act=list'));
	$smarty->display('ceping_question.htm');
}
if ($_REQUEST['act'] == 'add_question' || $_REQUEST['act'] == 'edit_question')
{
	admin_priv('ceping');

	$isadd     = $_REQUEST['act'] == 'add_question';
	$smarty->assign('isadd', $isadd);
	$question_id  = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);
	
	$exam_id = intval($_REQUEST['exam_id']);
	if (!$exam = $db->getRow('SELECT exam_id,title FROM '.$ecs->table('exam').' WHERE exam_id='.$exam_id)){
		sys_msg('套题不存在',1);
	}
	$smarty->assign('exam_id',$exam_id);
	$smarty->assign('ur_here',     $exam['title'].'-添加/编辑题目');
	$smarty->assign('action_link',  array('text' => '返回列表', 'href' => 'ceping.php?act=question&id='.$exam_id));
	assign_query_info();
	$smarty->assign('cfg_lang',   $_CFG['lang']);

	if (!$isadd)
	{
		$sql = "SELECT * FROM " . $ecs->table('exam_question') . " WHERE question_id = '$question_id'";
		$question = $db->getRow($sql);
	
		

		$smarty->assign('question', $question);
		$smarty->assign('act',   "update_question");
	}
	else
	{
		$smarty->assign('question', array('point_yes'=>1,'point_no'=>0));
		$smarty->assign('act', "insert_question");
	}
	$smarty->display('ceping_question_info.htm');
}
elseif ($_REQUEST['act'] == 'insert_question' || $_REQUEST['act'] == 'update_question')
{
	admin_priv('ceping');

	$is_insert = $_REQUEST['act'] == 'insert_question';
	$question_id  = empty($_POST['id']) ? 0 : intval($_POST['id']);
	$exam_id = empty($_POST['exam_id']) ? 0 : intval($_POST['exam_id']);
	$question = $_POST['question'];
	$point_yes = intval($_POST['point_yes']);
	$point_no = intval($_POST['point_no']);

	if ($is_insert)
	{
		$sql = "INSERT INTO " . $ecs->table('exam_question') . " (exam_id,question,point_yes,point_no) " .
				"VALUES ('$exam_id','$question','$point_yes','$point_no')";
		$links[] = array('href' => 'ceping.php?act=add_question&exam_id='.$exam_id, 'text' =>  '继续添加');
		admin_log($question, 'add', 'ceping');
	}
	else
	{ 
		if ($db->getOne('SELECT COUNT(*) FROM '.$ecs->table('exam_question').' WHERE question_id='.$question_id.' AND exam_id='.$exam_id)==0){
			sys_msg('题目不存在', 1);
		}
		$sql = "UPDATE " . $ecs->table('exam_question') .
		"SET question='$question',point_yes='$point_yes',point_no='$point_no'" .
		" WHERE question_id='$question_id' AND exam_id='$exam_id' LIMIT 1";
		admin_log($question, 'edit', 'ceping');

	}

	$db->query($sql);

	clear_cache_files();
	
	$links[] = array('href' => 'ceping.php?act=question&id='.$exam_id, 'text' =>  '返回题目列表');
	sys_msg('操作成功', 0, $links);
}
elseif ($_REQUEST['act'] == 'result')
{
	admin_priv('ceping');
	$smarty->assign('full_page',   1);
	
	$exam_id = intval($_REQUEST['id']);
	if (!$exam = $db->getRow('SELECT exam_id,title FROM '.$ecs->table('exam').' WHERE exam_id='.$exam_id)){
		sys_msg('套题不存在',1);
	}
	$sql = 'SELECT * FROM '.$ecs->table('exam_result').' WHERE exam_id='.$exam_id;
	$list = $db->getAll($sql);
	$smarty->assign('ur_here',     $exam['title'].'-结果列表');
	$smarty->assign('exam_id',$exam_id);
	$smarty->assign('result_list',   $list);
	assign_query_info();
	$smarty->assign('action_link', array('text' => '添加结果', 'href' => 'ceping.php?act=add_result&exam_id='.$exam_id));
	$smarty->assign('action_link2', array('text' => '套题列表', 'href' => 'ceping.php?act=list'));
	$smarty->display('ceping_result.htm');
}
if ($_REQUEST['act'] == 'add_result' || $_REQUEST['act'] == 'edit_result')
{
	admin_priv('ceping');

	$isadd     = $_REQUEST['act'] == 'add_result';
	$smarty->assign('isadd', $isadd);
	$result_id  = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);
	
	$exam_id = intval($_REQUEST['exam_id']);
	if (!$exam = $db->getRow('SELECT exam_id,title FROM '.$ecs->table('exam').' WHERE exam_id='.$exam_id)){
		sys_msg('套题不存在',1);
	}
	$smarty->assign('exam_id',$exam_id);
	$smarty->assign('ur_here',     $exam['title'].'-添加/编辑结果');
	$smarty->assign('action_link',  array('text' => '返回列表', 'href' => 'ceping.php?act=result&id='.$exam_id));
	$smarty->assign('cat_list',   cat_list(0));
	$smarty->assign('brand_list', get_brand_list());
	$smarty->assign('cfg_lang',   $_CFG['lang']);
	
	if (!$isadd)
	{
		$sql = "SELECT * FROM " . $ecs->table('exam_result') . " WHERE result_id = '$result_id'";
		$result = $db->getRow($sql);
		$result['goods'] = empty($result['goods'])?'[]':$result['goods'];
		

		$smarty->assign('result', $result);
		$smarty->assign('act',   "update_result");
	}
	else
	{
		$smarty->assign('result', array('goods'=>'[]'));
		$smarty->assign('act', "insert_result");
	}
	assign_query_info();
	$smarty->display('ceping_result_info.htm');
}
elseif ($_REQUEST['act'] == 'insert_result' || $_REQUEST['act'] == 'update_result')
{
	admin_priv('ceping');

	$is_insert = $_REQUEST['act'] == 'insert_result';
	$result_id  = empty($_POST['id']) ? 0 : intval($_POST['id']);
	$exam_id = empty($_POST['exam_id']) ? 0 : intval($_POST['exam_id']);
	$content = $_POST['content'];
	$point_min = intval($_POST['point_min']);
	$point_max = intval($_POST['point_max']);
	$result = $_POST['result'];
	$goods = $_POST['goods'];

	if ($is_insert)
	{
		$sql = "INSERT INTO " . $ecs->table('exam_result') . " (exam_id,content,point_min,point_max,result,goods) " .
				"VALUES ('$exam_id','$content','$point_min','$point_max','$result','$goods')";
		$links[] = array('href' => 'ceping.php?act=add_result&exam_id='.$exam_id, 'text' =>  '继续添加');
		admin_log('套题（'.$exam_id.'）结果', 'add', 'ceping');
	}
	else
	{ 
		if ($db->getOne('SELECT COUNT(*) FROM '.$ecs->table('exam_result').' WHERE result_id='.$result_id.' AND exam_id='.$exam_id)==0){
			sys_msg('该记录不存在', 1);
		}
		$sql = "UPDATE " . $ecs->table('exam_result') .
		"SET content='$content',point_min='$point_min',point_max='$point_max',result='$result',goods='$goods'" .
		" WHERE result_id='$result_id' AND exam_id='$exam_id' LIMIT 1";
		admin_log('套题（'.$exam_id.'）结果', 'edit', 'ceping');
	}

	$db->query($sql);

	clear_cache_files();

	$links[] = array('href' => 'ceping.php?act=result&id='.$exam_id, 'text' =>  '返回结果列表');
	sys_msg('操作成功', 0, $links);
}
elseif ($_REQUEST["act"] == "delete")
{
    admin_priv('ceping');

    $sql = "DELETE e,eq,er FROM " . $ecs->table('exam') . " AS e ".
      		"LEFT JOIN ".$ecs->table('exam_question')." AS eq ON e.exam_id=eq.exam_id ".
      		"LEFT JOIN ".$ecs->table('exam_result')." AS er ON e.exam_id=er.exam_id ".
    		"WHERE ";

    if (!empty($_POST['checkboxs']))
    {
        $sql .= db_create_in($_POST['checkboxs'], 'e.exam_id');
        $arr = $db->getCol('SELECT title FROM '.$ecs->table('exam').' WHERE '.db_create_in($_POST['checkboxs'],'exam_id'));
        $title = implode(',',$arr);
    }
    elseif (!empty($_GET['id']))
    {
        $_GET['id'] = intval($_GET['id']);
        $sql .= "e.exam_id = '$_GET[id]'";
        $title = $db->getCol('SELECT title FROM '.$ecs->table('exam').' WHERE exam_id='.$_GET['id']);
    }
    else
    {
        exit;
    }

    
    
    /* 删除原来的图片文件 */
    $sql1 = "SELECT icon " .
    		" FROM " . $ecs->table('exam') .
    		" WHERE exam_id = '$_GET[id]'";
    $row = $db->getRow($sql1);
    if ($row['icon'] != '' && is_file('../' . $row['icon']))
    {
    	@unlink('../' . $row['icon']);
    }
    
    $db->query($sql);
    clear_cache_files();
    admin_log($title, 'remove', 'ceping');
    if (!empty($_REQUEST['is_ajax']))
    {
        $url = 'ceping.php?act=query&' . str_replace('act=delete', '', $_SERVER['QUERY_STRING']);
        ecs_header("Location: $url\n");
        exit;
    }

    $links[] = array('href' => 'ceping.php', 'text' =>  $_LANG['back_list']);
    sys_msg('操作成功', 0, $links);
}
elseif ($_REQUEST["act"] == "query")
{
    $exam_list = get_exam_list();
    $smarty->assign('exam_list',   $exam_list['item']);
    $smarty->assign('filter',       $exam_list['filter']);
    $smarty->assign('record_count', $exam_list['record_count']);
    $smarty->assign('page_count',   $texam_listt['page_count']);
    $smarty->assign('use_storage',  empty($_CFG['use_storage']) ? 0 : 1);

    /* 排序标记 */
    $sort_flag  = sort_flag($exam_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    $tpl = 'ceping_list.htm';
    make_json_result($smarty->fetch($tpl), '',array('filter' => $exam_list['filter'], 'page_count' => $exam_list['page_count']));
}
elseif ($_REQUEST['act'] == 'toggle_selected')
{
	check_authz_json('ceping');

	$second_id       = intval($_POST['id']);
	$is_selected        = intval($_POST['val']);

	if ($exc->edit("is_selected = '$is_selected'", $second_id))
	{
		clear_cache_files();
		make_json_result($is_selected);
	}
}
elseif ($_REQUEST['act'] == 'edit_sort_order')
{
	check_authz_json('ceping');

	$exam_id       = intval($_POST['id']);
	$sort_order     = intval($_POST['val']);

	if ($exc->edit("ordering = '$sort_order'", $exam_id))
	{
		clear_cache_files();
		make_json_result($sort_order);
	}
}
elseif ($_REQUEST['act'] == 'edit_point_yes')
{
	check_authz_json('ceping');

	$question_id       = intval($_POST['id']);
	$point     = intval($_POST['val']);

	if ($exc2->edit("point_yes = '$point'", $question_id))
	{
		clear_cache_files();
		make_json_result($point);
	}
}
elseif ($_REQUEST['act'] == 'edit_point_no')
{
	check_authz_json('ceping');

	$question_id       = intval($_POST['id']);
	$point     = intval($_POST['val']);

	if ($exc2->edit("point_no = '$point'", $question_id))
	{
		clear_cache_files();
		make_json_result($point);
	}
}
elseif ($_REQUEST['act'] == 'edit_point_min')
{
	check_authz_json('ceping');

	$result_id       = intval($_POST['id']);
	$point     = intval($_POST['val']);

	if ($exc3->edit("point_min = '$point'", $result_id))
	{
		clear_cache_files();
		make_json_result($point);
	}
}
elseif ($_REQUEST['act'] == 'edit_point_max')
{
	check_authz_json('ceping');

	$result_id       = intval($_POST['id']);
	$point     = intval($_POST['val']);

	if ($exc3->edit("point_max = '$point'", $result_id))
	{
		clear_cache_files();
		make_json_result($point);
	}
}
elseif ($_REQUEST["act"] == "delete_question")
{
	admin_priv('ceping');

	$sql = "DELETE FROM " . $ecs->table('exam_question') . " WHERE ";

	if (!empty($_POST['checkboxs']))
	{
		$sql .= db_create_in($_POST['checkboxs'], 'question_id');
	}
	elseif (!empty($_GET['id']))
	{
		$_GET['id'] = intval($_GET['id']);
		$sql .= "question_id = '$_GET[id]'";
	}
	else
	{
		exit;
	}

	$db->query($sql);

	clear_cache_files();

	if (!empty($_REQUEST['is_ajax']))
	{
		$url = 'ceping.php?act=question&' . str_replace('act=delete_question', '', $_SERVER['QUERY_STRING']);
		ecs_header("Location: $url\n");
		exit;
	}

	$links[] = array('href' => 'ceping.php', 'text' =>  $_LANG['back_list']);
	sys_msg('操作成功', 0, $links);
}
elseif ($_REQUEST["act"] == "delete_result")
{
	admin_priv('ceping');

	$sql = "DELETE FROM " . $ecs->table('exam_result') . " WHERE ";

	if (!empty($_POST['checkboxs']))
	{
		$sql .= db_create_in($_POST['checkboxs'], 'result_id');
	}
	elseif (!empty($_GET['id']))
	{
		$_GET['id'] = intval($_GET['id']);
		$sql .= "result_id = '$_GET[id]'";
	}
	else
	{
		exit;
	}

	$db->query($sql);

	clear_cache_files();

	if (!empty($_REQUEST['is_ajax']))
	{
		$url = 'ceping.php?act=result&' . str_replace('act=delete_result', '', $_SERVER['QUERY_STRING']);
		ecs_header("Location: $url\n");
		exit;
	}

	$links[] = array('href' => 'ceping.php', 'text' =>  $_LANG['back_list']);
	sys_msg('操作成功', 0, $links);
}
elseif ($_REQUEST['act'] == 'get_goods_list')
{
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON;

	$filters = $json->decode($_GET['JSON']);
	$filters->is_on_sale = 1;
	$filters->is_alone_sale = 1;
	$arr = get_goods_list($filters);
	$opt = array();

	foreach ($arr AS $key => $val)
	{
		$opt[] = array('value' => $val['goods_id'],
				'text'  => $val['goods_name'],
				'data' => $val['shop_price']
		);
	}

	make_json_result($opt);
}

/**
 * 获取题库列表
 * @access  public
 * @return void
 */
function get_exam_list()
{
    $result = get_filter();
    if ($result === false)
    {
        /* 查询条件 */
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'exam_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        $sql = "SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('exam');
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        /* 分页大小 */
        $filter = page_and_size($filter);

        $sql = "SELECT * FROM " .$GLOBALS['ecs']->table('exam'). " ORDER BY $filter[sort_by] $filter[sort_order]";

        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }

    $query = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $res = array();

    while($exam = $GLOBALS['db']->fetch_array($query)){
        $exam['created']   = local_date('Y-m-d',$exam['created']);
        $exam['edit_url']        = 'ceping.php?act=edit_exam&id=' . $exam['exam_id'];
        $exam['question_url']        = 'ceping.php?act=question&id=' . $exam['exam_id'];
        $exam['result_url']        = 'ceping.php?act=result&id=' . $exam['exam_id'];
        $res[] = $exam;
    }

    $arr = array('item' => $res, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

    return $arr;
}


?>
